package com.cxq.boot.controller;

import com.cxq.boot.dto.FileDTO;
import com.cxq.boot.provider.UCloudProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//处理文件上传
@Controller
public class FileController {

    @Autowired
    private UCloudProvider uCloudProvider;

    /**
     * 前端上传图片有大小限制，查看文档是否可修改
     * @param request
     * @return
     */
    @RequestMapping(value = "/file/upload")
    @ResponseBody
    public FileDTO upload(HttpServletRequest request){
        //通过MultipartHttpServletRequest利用multipart请求将本地文件上传到服务器
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        //multipartRequest通过文件名直接拿到文件
        MultipartFile file = multipartRequest.getFile("editormd-image-file");//上传本地文件按钮name="editormd-image-file"
        try {
            long fileSize = file.getSize();//返回文件的大小
            String fileName = uCloudProvider.upload(file.getInputStream(), fileSize, file.getContentType(), file.getOriginalFilename());

            //设置返回前端的值
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            //fileDTO.setMessage("上传成功");
            fileDTO.setUrl(fileName);
            return fileDTO;
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileDTO fileDTO = new FileDTO();
        fileDTO.setSuccess(1);
        //fileDTO.setMessage("上传成功");
        fileDTO.setUrl("/images/guanggao.png");
        return fileDTO;
    }
}
